package com.ruoyi.matrix.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.matrix.service.DingtalkService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.matrix.service.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DingtalkServiceImpl implements DingtalkService {

    private static final String prefix = "[Matrix]:\n";
    private static final String dingTalkUrl = "https://oapi.dingtalk.com/robot/send?access_token=f8f1e9ed8e67085582693bfb216b2a1888c789bda7a64e046d4e4d1ddb2cacd1";
    private static final Logger log = LoggerFactory.getLogger(DingtalkServiceImpl.class);


    @Autowired
    private RequestUtils requestUtils;

    @Override
    public void send(String text) {
        // machine
        String host = "unknown";
        String ip = "127.0.0.1";
        try {
            InetAddress ia = InetAddress.getLocalHost();
            host = ia.getHostName();//获取计算机主机名
            ip = ia.getHostAddress();//获取计算机IP
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


        String str = prefix
                + DateUtils.format(new Date()) + "\n"
                + "From " + host + "@" + ip + " Reported:\n"
                + text;

        if (str != null && str.length() > 1500) {
            str = str.substring(0, 1500);
        }

        Map<String, Object> content = new HashMap<>();
        content.put("msgtype", "text");
        Map<String, Object> body = new HashMap<>();
        body.put("content", str);
        Map<String, Object> at = new HashMap<>();
        at.put("atMobiles", new ArrayList<String>());
        at.put("isAtAll", false);

        content.put("text", body);
        content.put("at", at);


        String postContent = JSONObject.toJSONString(content);

        if (!StringUtils.isBlank(postContent)) {
            try {

                String r = this.requestUtils.doPost(dingTalkUrl, postContent, "application/json");
                log.info("result->{}", JSON.toJSONString(r));

            } catch (Exception ex) {
                log.error("HttpClientUtil发送异常, 异常：" + ex.getMessage(), ex.getCause());
            }
        }

    }
}
